package cn.edu.scau.cmi.chenbingquan.client;

import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationContext;
import cn.edu.scau.cmi.chenbingquan.comprehension.dao.StudentDAO;
import cn.edu.scau.cmi.chenbingquan.comprehension.dao.TeacherDAO;
import cn.edu.scau.cmi.chenbingquan.comprehension.domain.Student;
import cn.edu.scau.cmi.chenbingquan.comprehension.domain.Teacher;
import cn.edu.scau.cmi.chenbingquan.spring.util.ApplicationContextUtil;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class SpringHibernateSessionClient extends Application {
	private Pane root = new Pane();
	private ComboBox<String> comboBox;
	private Button sure;
	private ListView<Text> lv = new ListView<>();
	private ArrayList<Student> students = new ArrayList<>();
	private ArrayList<Teacher> teachers = new ArrayList<>();
	
	public static void main(String[] args) {
		launch(args);
	}
	
	@Override
	public void start(Stage stage) {
		root.setStyle("-fx-background-color: linear-gradient(to bottom right, ANTIQUEWHITE, CORNFLOWERBLUE)");
		root.setPrefSize(550, 450);
		
		comboBox = new ComboBox<>();
		comboBox.getItems().addAll("1.添加学生", "2.删除学生", "3.修改学生", "4.学生选择老师（单选）", "5.显示学生表信息",
				 				   "6.添加老师", "7.删除老师", "8.修改老师", "9.老师选择学生（多选）", "10.显示老师表信息");
		comboBox.setVisibleRowCount(4);
		comboBox.setPromptText("请选择：");
		comboBox.setPrefSize(180, 35);
		comboBox.setLayoutX(60);
		comboBox.setLayoutY(70);
		
		sure = new Button("确定");
		sure.setPrefSize(60, 35);
		sure.setLayoutX(270);
		sure.setLayoutY(70);
		
		lv.setPrefSize(445, 280);
		lv.setFixedCellSize(30);
		lv.setLayoutX(60);
		lv.setLayoutY(150);
		root.getChildren().addAll(comboBox, sure, lv);
		
		Scene scene = new Scene(root);
		stage.setScene(scene);
		stage.getIcons().add(new Image("cn/edu/scau/cmi/chenbingquan/image/窗口左上角图标.png"));
		stage.setTitle("老师指导学生毕业设计");
		stage.setResizable(false);
		stage.show();
		
		addEvents();	// 添加事件
	}
	
	// 添加事件
	private void addEvents() {
		// 获取数据库中的数据
		getDataFromDatabase();
			
		// 确定按钮点击事件
		sure.setOnMouseClicked(action -> {
			String select = comboBox.getValue();
			if(select == null) {
				showMessageStage("请先选择操作!!");
			} else if(select.equals("1.添加学生")) {
				showAddStage(true);
			} else if(select.equals("2.删除学生")) {
				showDeleteStage(true);
			} else if(select.equals("3.修改学生")) {
				showUpdateStage(true);
			} else if(select.equals("4.学生选择老师（单选）")) {
				showSelectStage(true);
			} else if(select.equals("5.显示学生表信息")) {
				listAllMessage(true);
			} else if(select.equals("6.添加老师")) {
				showAddStage(false);
			} else if(select.equals("7.删除老师")) {
				showDeleteStage(false);
			} else if(select.equals("8.修改老师")) {
				showUpdateStage(false);
			} else if(select.equals("9.老师选择学生（多选）")) {
				showSelectStage(false);
			} else if(select.equals("10.显示老师表信息")) {
				listAllMessage(false);
			}
		});
	}
		
	// 获取数据库中数据并读入学生和教师数组
	private void getDataFromDatabase() {
		List<?> teacherList = new TeacherDAO().findAll();
		teachers.clear();
		for(int i=0; i<teacherList.size(); i++) {
			teachers.add((Teacher)teacherList.get(i));
		}
		
		List<?> studentList = new StudentDAO().findAll();
		students.clear();
		for(int i=0; i<studentList.size(); i++) {
			students.add((Student)studentList.get(i));
		}
	}
	
	// 添加老师或学生
	private void showAddStage(boolean isStudent) {
		Pane pane = new Pane();
		pane.setStyle("-fx-background-color: #44A08D");
					
		TextField tf = new TextField();
		tf.setFocusTraversable(false);
		tf.setPromptText("请输入名字");
		tf.setPrefHeight(40);
		tf.setLayoutX(70);
		tf.setLayoutY(50);
		
		Button button = new Button("确定");
		button.setPrefSize(60, 30);
		button.setLayoutX(120);
		button.setLayoutY(150);
		pane.getChildren().addAll(tf, button);
					
		Stage stage = new Stage();
		Scene scene = new Scene(pane, 300, 250);
		stage.setScene(scene);
		stage.show();
		
		ApplicationContext ac = ApplicationContextUtil.getApplicationContext();
		TeacherDAO teacherDAO = (TeacherDAO)ac.getBean("teacherDAO");
		StudentDAO studentDAO = (StudentDAO)ac.getBean("studentDAO");
		
		// 事件
		button.setOnMouseClicked(atcion -> {
			if(tf.getText().equals("")) {
				showMessageStage("请先输入名字!!");
			} else if(isStudent == true) {
				boolean isExisted = false;
				for(int i=0; i<students.size(); i++) {
					Student temp = students.get(i);
					if(temp.getName().equals(tf.getText())) {
						isExisted = true;
						showMessageStage("该学生已经存在!!");
						break;
					}
				}
				if(isExisted == false) {
					Student student = new Student();
					student.setName(tf.getText());
					studentDAO.save(student);
					showMessageStage("添加成功!!");
					getDataFromDatabase();
				}
				
			} else if(isStudent == false) {
				boolean isExisted = false;
				for(int i=0; i<teachers.size(); i++) {
					Teacher temp = teachers.get(i);
					if(temp.getName().equals(tf.getText())) {
						isExisted = true;
						showMessageStage("该老师已经存在!!");
						break;
					}
				}
				if(isExisted == false) {
					Teacher teacher = new Teacher();
					teacher.setName(tf.getText());
					teacherDAO.save(teacher);
					showMessageStage("添加成功!!");
					getDataFromDatabase();
				}
			}
			stage.close();
		}); 		
	}

	// 删除学生或老师
	private void showDeleteStage(boolean isStudent) {
		Pane pane = new Pane();
		pane.setStyle("-fx-background-color: #44A08D");
					
		TextField tf = new TextField();
		tf.setFocusTraversable(false);
		tf.setPromptText("请输入学生学号或教师工号");
		tf.setPrefHeight(40);
		tf.setLayoutX(70);
		tf.setLayoutY(50);
		
		Button button = new Button("确定");
		button.setPrefSize(60, 30);
		button.setLayoutX(120);
		button.setLayoutY(150);
		pane.getChildren().addAll(tf, button);
					
		Stage stage = new Stage();
		Scene scene = new Scene(pane, 300, 250);
		stage.setScene(scene);
		stage.show();
		
		ApplicationContext ac = ApplicationContextUtil.getApplicationContext();
		TeacherDAO teacherDAO = (TeacherDAO)ac.getBean("teacherDAO");
		StudentDAO studentDAO = (StudentDAO)ac.getBean("studentDAO");
		
		// 确定按钮点击事件
		button.setOnMouseClicked(action -> {
			if(tf.getText().equals("")) {
				showMessageStage("请先输入信息!!");
			} else if(isStudent == true) {
				boolean isExisted = false;
				for(int i=0; i<students.size(); i++) {
					Student temp = students.get(i);
					if(temp.getId() == Long.valueOf(tf.getText())) {
						isExisted = true;
						studentDAO.delete(temp);
						showMessageStage("删除成功!!");
						getDataFromDatabase();
						break;
					}
				}
				if(isExisted == false) {
					showMessageStage("该学生不存在!!");
				}
			} else if(isStudent == false) {
				boolean isExisted = false;
				for(int i=0; i<teachers.size(); i++) {
					Teacher temp = teachers.get(i);
					if(temp.getId() == Long.valueOf(tf.getText())) {
						isExisted = true;
						teacherDAO.delete(temp);
						showMessageStage("删除成功!!");
						getDataFromDatabase();
						break;
					}
				}
				if(isExisted == false) {
					showMessageStage("该老师不存在!!");
				}
			}
			stage.close();
		});
	}
	
	// 修改学生或老师信息
	private void showUpdateStage(boolean isStudent) {
		Pane pane = new Pane();
		pane.setStyle("-fx-background-color: #44A08D");
					
		TextField tf1 = new TextField();
		tf1.setFocusTraversable(false);
		tf1.setPromptText("请输入学生学号或教师工号");
		tf1.setPrefHeight(40);
		tf1.setLayoutX(70);
		tf1.setLayoutY(30);
		
		TextField tf2 = new TextField();
		tf2.setFocusTraversable(false);
		tf2.setPromptText("请输入新的名字");
		tf2.setPrefHeight(40);
		tf2.setLayoutX(70);
		tf2.setLayoutY(90);
		
		Button button = new Button("确定");
		button.setPrefSize(60, 30);
		button.setLayoutX(120);
		button.setLayoutY(160);
		pane.getChildren().addAll(tf1, tf2, button);
					
		Stage stage = new Stage();
		Scene scene = new Scene(pane, 300, 250);
		stage.setScene(scene);
		stage.show();
		
		ApplicationContext ac = ApplicationContextUtil.getApplicationContext();
		TeacherDAO teacherDAO = (TeacherDAO)ac.getBean("teacherDAO");
		StudentDAO studentDAO = (StudentDAO)ac.getBean("studentDAO");
		
		// 确定按钮点击事件
		button.setOnMouseClicked(action -> {
			if(tf1.getText().equals("") || tf2.getText().equals("")) {
				showMessageStage("请先输入完整信息!!");
			} else if(isStudent == true) {
				boolean isExisted = false;
				for(int i=0; i<students.size(); i++) {
					Student temp = students.get(i);
					if(temp.getId() == Long.valueOf(tf1.getText())) {
						isExisted = true;
						temp.setName(tf2.getText());
						studentDAO.update(temp);
						showMessageStage("修改成功!!");
						getDataFromDatabase();
						break;
					}
				}
				if(isExisted == false) {
					showMessageStage("该学生不存在!!");
				}
			} else if(isStudent == false) {
				boolean isExisted = false;
				for(int i=0; i<teachers.size(); i++) {
					Teacher temp = teachers.get(i);
					if(temp.getId() == Long.valueOf(tf1.getText())) {
						isExisted = true;
						temp.setName(tf2.getText());
						teacherDAO.update(temp);
						showMessageStage("修改成功!!");
						getDataFromDatabase();
						break;
					}
				}
				if(isExisted == false) {
					showMessageStage("该老师不存在!!");
				}
			}
			stage.close();
		});
	}
	
	// 学生选择老师(单选)或老师选择学生(多选)
	private void showSelectStage(boolean isStudent) {
		Pane pane = new Pane();
		pane.setStyle("-fx-background-color: #44A08D");
					
		TextField tf1 = new TextField();
		tf1.setFocusTraversable(false);
		tf1.setPromptText("请输入学生学号");
		tf1.setPrefHeight(40);
		tf1.setLayoutX(70);
		tf1.setLayoutY(30);
		
		TextField tf2 = new TextField();
		tf2.setFocusTraversable(false);
		tf2.setPromptText("请输入教师工号");
		tf2.setPrefHeight(40);
		tf2.setLayoutX(70);
		tf2.setLayoutY(90);
		
		Button button = new Button("确定");
		button.setPrefSize(60, 30);
		button.setLayoutX(120);
		button.setLayoutY(160);
		pane.getChildren().addAll(tf1, tf2, button);
					
		Stage stage = new Stage();
		Scene scene = new Scene(pane, 300, 250);
		stage.setScene(scene);
		stage.show();
		
		ApplicationContext ac = ApplicationContextUtil.getApplicationContext();
		TeacherDAO teacherDAO = (TeacherDAO)ac.getBean("teacherDAO");
		StudentDAO studentDAO = (StudentDAO)ac.getBean("studentDAO");
		
		// 确定按钮点击事件
		button.setOnMouseClicked(action -> {
			if(tf1.getText().equals("") || tf2.getText().equals("")) {
				showMessageStage("请先输入完整信息!!");
			} else if(isStudent == true) {
				boolean isExisted = false;
				for(int i=0; i<students.size(); i++) {
					Student temp = students.get(i);
					if(temp.getId() == Long.valueOf(tf1.getText())) {
						isExisted = true;
						if(temp.getTeacher() == null) {
							if(isTeacherExisted(Long.valueOf(tf2.getText())) != null) {
								temp.setTeacher(new Teacher(Long.valueOf(tf2.getText())));
								studentDAO.selectTeacher(temp);
								showMessageStage("选择成功!!");
								getDataFromDatabase();
							} else {
								showMessageStage("要选择的教师不存在!!");
							}
						} else {
							showMessageStage("该学生已有老师!!");
						}
						break;
					}
				}
				if(isExisted == false) {
					showMessageStage("该学生不存在!!");
				}
			} else if(isStudent == false) {
				boolean isExisted = false;
				for(int i=0; i<teachers.size(); i++) {
					Teacher temp = teachers.get(i);
					if(temp.getId() == Long.valueOf(tf2.getText())) {
						isExisted = true;
						Student student = isStudentExisted(Long.valueOf(tf1.getText()));
						if(student != null) {
							if(student.getTeacher() != null) {
								showMessageStage("要选择的学生已有老师!!");
							} else {
								teacherDAO.selectStudent(temp, Long.valueOf(tf1.getText()));
								showMessageStage("选择成功!!");
								getDataFromDatabase();
							}
						} else {
							showMessageStage("要选择的学生不存在!!");
						}
						break;
					} 
				}
				if(isExisted == false) {
					showMessageStage("该教师不存在!!");
				}
			}
			stage.close();
		});
	}
	
	// 显示学生表或教师表信息
	private void listAllMessage(boolean isStudent) {
		if(isStudent == true) {
			lv.getItems().clear();
			lv.getItems().add(new Text("学生学号\t\t名字\t\t指导老师工号"));
			for(int i=0; i<students.size(); i++) {
				Student temp = students.get(i);
				String str;
				if(temp.getTeacher() == null) {
					str = "无";
				} else {
					str = String.valueOf(temp.getTeacher().getId());
				}
				Text text = new Text(temp.getId() + "\t\t" + temp.getName() + "\t\t" + str);
				text.setFill(Color.DODGERBLUE);
				lv.getItems().add(text);
			}
		} else if(isStudent == false) {
			lv.getItems().clear();
			lv.getItems().add(new Text("教师工号\t\t名字"));
			for(int i=0; i<teachers.size(); i++) {
				Teacher temp = teachers.get(i);
				Text text = new Text(temp.getId() + "\t\t" + temp.getName());
				text.setFill(Color.RED);
				lv.getItems().add(text);
			}
		}
	}
	
	// 判断指定工号的教师是否存在
	private Teacher isTeacherExisted(Long id) {
		for(int i=0; i<teachers.size(); i++) {
			Teacher temp = teachers.get(i);
			if(temp.getId() == id) {
				return temp;
			}
		}
		return null;
	}
	
	// 判断指定学号的学生是否存在
	private Student isStudentExisted(Long id) {
		for(int i=0; i<students.size(); i++) {
			Student temp = students.get(i);
			if(temp.getId() == id) {
				return temp;
			}
		}
		return null;
	}
	
	// 显示信息窗口
	private void showMessageStage(String message) {
		VBox vBox = new VBox(60);
		vBox.setAlignment(Pos.CENTER);
		vBox.setStyle("-fx-background-color: ANTIQUEWHITE");
		vBox.setPrefSize(300, 250);
					
		Text text = new Text(message);
		text.setStyle("-fx-font-size: 25; -fx-fill: orange"); 
					
		Button button = new Button("确定");
		button.setPrefSize(60, 30);
		vBox.getChildren().addAll(text, button);
					
		Stage stage = new Stage();
		Scene scene = new Scene(vBox);
		stage.setScene(scene);
		stage.show();
					
		// 事件
		button.setOnMouseClicked(e -> stage.close() ); 		// 关闭窗口
	}
}
